package com.sukaiyi.leetcode._6zigzag_conversion;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * 将一个给定字符串根据给定的行数，以从上往下、从左到右进行 Z 字形排列。
 * <p>
 * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时，排列如下：
 * <p>
 * L   C   I   R
 * E T O E S I I G
 * E   D   H   N
 * 之后，你的输出需要从左往右逐行读取，产生出一个新的字符串，比如："LCIRETOESIIGEDHN"。
 *
 * @author sukaiyi
 * @date 2020/08/25
 * @see <a href="https://leetcode-cn.com/problems/zigzag-conversion/">题目地址</a>
 */
public class Solution {

    public String convert(String s, int numRows) {
        if (s.length() <= 2 || numRows == 1) {
            return s;
        }
        int length = s.length();
        int cols = (length / (2 * numRows - 2) + 1) * (numRows - 1);
        char[][] m = new char[numRows][];
        int[] index = new int[numRows];
        for (int i = 0; i < numRows; i++) {
            m[i] = new char[cols];
        }
        char[] chars = s.toCharArray();
        for (int i = 0, pos = 0, direct = 1; i < chars.length; i++) {
            m[pos][index[pos]++] = chars[i];
            pos += direct;
            if (pos == 0) {
                direct = 1;
            }
            if (pos == numRows - 1) {
                direct = -1;
            }
        }
        for (int i = 0, pos = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++) {
                if (m[i][j] > 0) {
                    chars[pos++] = m[i][j];
                }
            }
        }
        return new String(chars);
    }

    @Test
    public void testCase() {
        Assertions.assertEquals("PAHNAPLSIIGYIR", convert("PAYPALISHIRING", 3));
        Assertions.assertEquals("LCIRETOESIIGEDHN", convert("LEETCODEISHIRING", 3));
    }

}
